/**
 * 路由配置
 */
import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import { globalAuth } from '@/composables/useAuth'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'

// 路由配置
const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/Login.vue'),
    meta: {
      title: '登录',
      requiresAuth: false,
      hideInMenu: true
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/auth/Register.vue'),
    meta: {
      title: '注册',
      requiresAuth: false,
      hideInMenu: true
    }
  },
  {
    path: '/',
    component: () => import('@/layouts/MainLayout.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/Index.vue'),
        meta: {
          title: '仪表盘',
          icon: 'Dashboard',
          requiresAuth: true
        }
      },
      // 学生管理
      {
        path: 'students',
        name: 'Students',
        redirect: '/students/list',
        meta: {
          title: '学生管理',
          icon: 'User',
          requiresAuth: true,
          roles: ['admin', 'teacher']
        },
        children: [
          {
            path: 'list',
            name: 'StudentList',
            component: () => import('@/views/students/StudentList.vue'),
            meta: {
              title: '学生列表',
              requiresAuth: true,
              roles: ['admin', 'teacher']
            }
          },
          {
            path: 'create',
            name: 'StudentCreate',
            component: () => import('@/views/students/StudentForm.vue'),
            meta: {
              title: '添加学生',
              requiresAuth: true,
              roles: ['admin', 'teacher']
            }
          },
          {
            path: ':id/edit',
            name: 'StudentEdit',
            component: () => import('@/views/students/StudentForm.vue'),
            meta: {
              title: '编辑学生',
              requiresAuth: true,
              roles: ['admin', 'teacher'],
              hideInMenu: true
            }
          },
          {
            path: ':id/detail',
            name: 'StudentDetail',
            component: () => import('@/views/students/StudentDetail.vue'),
            meta: {
              title: '学生详情',
              requiresAuth: true,
              hideInMenu: true
            }
          },
          {
            path: 'import',
            name: 'StudentImport',
            component: () => import('@/views/students/StudentImport.vue'),
            meta: {
              title: '批量导入',
              requiresAuth: true,
              roles: ['admin']
            }
          },
          {
            path: 'statistics',
            name: 'StudentStatistics',
            component: () => import('@/views/students/StudentStatistics.vue'),
            meta: {
              title: '学生统计',
              requiresAuth: true,
              roles: ['admin', 'teacher']
            }
          }
        ]
      },
      // 简历管理
      {
        path: 'resume',
        name: 'Resume',
        redirect: '/resume/my',
        meta: {
          title: '简历管理',
          icon: 'Document',
          requiresAuth: true
        },
        children: [
          {
            path: 'my',
            name: 'MyResume',
            component: () => import('@/views/resume/ResumeList.vue'),
            meta: {
              title: '我的简历',
              requiresAuth: true,
              roles: ['student']
            }
          },
          {
            path: 'builder/:id',
            name: 'ResumeBuilder',
            component: () => import('@/views/resume/ResumeBuilder.vue'),
            meta: {
              title: '简历制作',
              requiresAuth: true,
              roles: ['student']
            }
          },
          {
            path: 'detail/:id',
            name: 'ResumeDetail',
            component: () => import('@/views/resume/ResumeDetail.vue'),
            meta: {
              title: '简历详情',
              requiresAuth: true,
              roles: ['student'],
              hideInMenu: true
            }
          },
          {
            path: 'review',
            name: 'ResumeReview',
            component: () => import('@/views/teacher/ResumeReview.vue'),
            meta: {
              title: '简历审核',
              requiresAuth: true,
              roles: ['admin', 'teacher']
            }
          },
          {
            path: 'reviewed',
            name: 'ReviewedResumeList',
            component: () => import('@/views/teacher/ReviewedResumeList.vue'),
            meta: {
              title: '已审批简历',
              requiresAuth: true,
              roles: ['admin', 'teacher']
            }
          },
          {
            path: 'templates',
            name: 'ResumeTemplates',
            component: () => import('@/views/admin/ResumeTemplateManagement.vue'),
            meta: {
              title: '简历模板管理',
              requiresAuth: true,
              roles: ['admin']
            }
          },
          {
            path: 'management',
            name: 'ResumeManagement',
            component: () => import('@/views/admin/ResumeManagement.vue'),
            meta: {
              title: '全局简历管理',
              requiresAuth: true,
              roles: ['admin']
            }
          }
        ]
      },
      // 面试管理
      {
        path: 'interviews',
        name: 'Interviews',
        redirect: 'interviews/my',
        meta: {
          title: '面试管理',
          icon: 'ChatDotRound',
          requiresAuth: true
        },
        children: [
          {
            path: 'my',
            name: 'MyInterviews',
            component: () => import('@/views/students/InterviewList.vue'),
            meta: {
              title: '我的面试',
              requiresAuth: true,
              roles: ['student']
            }
          },
          {
            path: 'practice',
            name: 'InterviewPractice',
            component: () => import('@/views/students/InterviewPractice.vue'),
            meta: {
              title: '面试练习',
              requiresAuth: true,
              roles: ['student']
            }
          },
          {
            path: 'practice/chat/:jobId',
            name: 'InterviewPracticeChat',
            component: () => import('@/views/students/InterviewPracticeChat.vue'),
            meta: {
              title: '面试练习聊天',
              requiresAuth: true,
              roles: ['student'],
              hideInMenu: true
            }
          },
          {
            path: 'applications',
            name: 'InterviewApplications',
            component: () => import('@/views/teacher/InterviewApplications.vue'),
            meta: {
              title: '面试预约申请',
              requiresAuth: true,
              roles: ['admin', 'teacher']
            }
          },
          {
            path: 'schedule',
            name: 'InterviewSchedule',
            component: () => import('@/views/teacher/InterviewSchedule.vue'),
            meta: {
              title: '面试安排',
              requiresAuth: true,
              roles: ['admin', 'teacher']
            }
          },
          {
            path: 'questions',
            name: 'InterviewQuestions',
            component: () => import('@/views/teacher/InterviewQuestions.vue'),
            meta: {
              title: '题库管理',
              requiresAuth: true,
              roles: ['admin', 'teacher']
            }
          },
          {
            path: 'statistics',
            name: 'InterviewStatistics',
            component: () => import('@/views/teacher/InterviewStatistics.vue'),
            meta: {
              title: '面试统计',
              requiresAuth: true,
              roles: ['admin', 'teacher']
            }
          },
          {
            path: 'result/:id',
            name: 'InterviewResult',
            component: () => import('@/views/interviews/InterviewResult.vue'),
            meta: {
              title: '面试结果',
              requiresAuth: true
            }
          },
          {
            path: 'detail/:id',
            name: 'InterviewDetail',
            component: () => import('@/views/interviews/InterviewDetail.vue'),
            meta: {
              title: '面试详情',
              requiresAuth: true,
              hideInMenu: true
            }
          }
        ]
      },
      // 岗位管理
      {
        path: 'jobs',
        name: 'Jobs',
        redirect: '/jobs/list',
        meta: {
          title: '岗位管理',
          icon: 'Briefcase',
          requiresAuth: true
        },
        children: [
          {
            path: 'list',
            name: 'JobList',
            component: () => import('@/views/jobs/JobList.vue'),
            meta: {
              title: '岗位列表',
              requiresAuth: true
            }
          },
          {
            path: 'create',
            name: 'JobCreate',
            component: () => import('@/views/jobs/JobForm.vue'),
            meta: {
              title: '发布岗位',
              requiresAuth: true,
              roles: ['admin', 'teacher']
            }
          },
          {
            path: ':id/edit',
            name: 'JobEdit',
            component: () => import('@/views/jobs/JobForm.vue'),
            meta: {
              title: '编辑岗位',
              requiresAuth: true,
              roles: ['admin', 'teacher'],
              hideInMenu: true
            }
          },
          {
            path: ':id/detail',
            name: 'JobDetail',
            component: () => import('@/views/jobs/JobDetail.vue'),
            meta: {
              title: '岗位详情',
              requiresAuth: true,
              hideInMenu: true
            }
          },
          {
            path: 'applications',
            name: 'JobApplications',
            component: () => import('@/views/jobs/JobApplications.vue'),
            meta: {
              title: '申请管理',
              requiresAuth: true,
              roles: ['admin', 'teacher']
            }
          },
          {
            path: 'my-applications',
            name: 'MyJobApplications',
            component: () => import('@/views/jobs/MyJobApplications.vue'),
            meta: {
              title: '我的申请',
              requiresAuth: true,
              roles: ['student']
            }
          },
          {
            path: 'my-applications',
            name: 'MyJobApplications',
            component: () => import('@/views/jobs/MyJobApplications.vue'),
            meta: {
              title: '我的申请',
              requiresAuth: true,
              roles: ['student']
            }
          },
          {
            path: 'companies',
            name: 'Companies',
            component: () => import('@/views/jobs/Companies.vue'),
            meta: {
              title: '公司管理',
              requiresAuth: true,
              roles: ['admin', 'teacher']
            }
          },
          {
            path: 'statistics',
            name: 'JobStatistics',
            component: () => import('@/views/jobs/JobStatistics.vue'),
            meta: {
              title: '岗位统计',
              requiresAuth: true,
              roles: ['admin', 'teacher']
            }
          }
        ]
      },
      // 通知中心
      {
        path: 'notifications',
        name: 'Notifications',
        component: () => import('@/views/notifications/NotificationList.vue'),
        meta: {
          title: '通知中心',
          icon: 'Bell',
          requiresAuth: true
        }
      },
      // 发送通知
      {
        path: 'notifications/send',
        name: 'SendNotification',
        component: () => import('@/views/notifications/SendNotification.vue'),
        meta: {
          title: '发送通知',
          requiresAuth: true,
          roles: ['admin', 'teacher']
        }
      },
      // 文件管理
      {
        path: 'files',
        name: 'Files',
        component: () => import('@/views/files/FileList.vue'),
        meta: {
          title: '文件管理',
          icon: 'Folder',
          requiresAuth: true,
          roles: ['admin', 'teacher']
        }
      },
      // 系统管理
      {
        path: 'system',
        name: 'System',
        redirect: '/system/users',
        meta: {
          title: '系统管理',
          icon: 'Setting',
          requiresAuth: true,
          roles: ['admin']
        },
        children: [
          {
            path: 'users',
            name: 'SystemUsers',
            component: () => import('@/views/system/UserManage.vue'),
            meta: {
              title: '用户管理',
              requiresAuth: true,
              roles: ['admin']
            }
          },
          {
            path: 'roles',
            name: 'SystemRoles',
            component: () => import('@/views/system/RoleManage.vue'),
            meta: {
              title: '角色权限',
              requiresAuth: true,
              roles: ['admin']
            }
          },
          {
            path: 'logs',
            name: 'SystemLogs',
            component: () => import('@/views/system/SystemLogs.vue'),
            meta: {
              title: '系统日志',
              requiresAuth: true,
              roles: ['admin']
            }
          },
          {
            path: 'student-advisor',
            name: 'StudentAdvisorManagement',
            component: () => import('@/views/admin/StudentAdvisorManagement.vue'),
            meta: {
              title: '学生指导老师分配',
              requiresAuth: true,
              roles: ['admin']
            }
          },
          {
            path: 'settings',
            name: 'SystemSettings',
            component: () => import('@/views/system/SystemSettings.vue'),
            meta: {
              title: '系统设置',
              requiresAuth: true,
              roles: ['admin']
            }
          },
          {
            path: 'schools',
            name: 'SystemSchools',
            component: () => import('@/views/system/SchoolManage.vue'),
            meta: {
              title: '校区管理',
              requiresAuth: true,
              roles: ['admin']
            }
          },
          {
            path: 'majors',
            name: 'SystemMajors',
            component: () => import('@/views/system/MajorManage.vue'),
            meta: {
              title: '专业管理',
              requiresAuth: true,
              roles: ['admin']
            }
          },
          {
            path: 'grades',
            name: 'SystemGrades',
            component: () => import('@/views/system/GradeManage.vue'),
            meta: {
              title: '年级管理',
              requiresAuth: true,
              roles: ['admin']
            }
          }
        ]
      },
      // 个人中心
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/profile/PersonalCenter.vue'),
        meta: {
          title: '个人中心',
          requiresAuth: true,
          hideInMenu: true
        }
      }
    ]
  },
  // 演示页面
  {
    path: '/demo/preview',
    name: 'PreviewDemo',
    component: () => import('@/views/demo/PreviewDemo.vue'),
    meta: {
      title: '预览功能演示',
      requiresAuth: false,
      hideInMenu: true
    }
  },
  // 测试页面
  {
    path: '/test/resume',
    name: 'ResumeTest',
    component: () => import('@/views/test/ResumeTest.vue'),
    meta: {
      title: '简历功能测试',
      requiresAuth: true,
      hideInMenu: true
    }
  },
  {
    path: '/test/vue-office',
    name: 'VueOfficeTest',
    component: () => import('@/views/test/VueOfficeTest.vue'),
    meta: {
      title: 'Vue-Office测试',
      requiresAuth: true,
      hideInMenu: true
    }
  },
  // 404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/error/404.vue'),
    meta: {
      title: '页面不存在',
      hideInMenu: true
    }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start()

  const userStore = useUserStore()
  const appStore = useAppStore()

  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 鸥鹏超级面试官`
  }

  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    // 如果正在初始化认证状态，等待完成
    if (globalAuth.isInitializing.value) {
      // 等待初始化完成
      const maxWait = 5000 // 最多等待5秒
      const startTime = Date.now()

      while (globalAuth.isInitializing.value && (Date.now() - startTime) < maxWait) {
        await new Promise(resolve => setTimeout(resolve, 100))
      }
    }

    // 如果有token但没有用户信息，尝试获取用户信息
    if (userStore.token && !userStore.userInfo && !globalAuth.isInitializing.value) {
      globalAuth.setInitializing(true)

      try {
        await userStore.initUserInfo()
        globalAuth.setError(null)
      } catch (error: any) {
        console.error('获取用户信息失败:', error)
        globalAuth.setError(error.message || '认证失败')

        // 只有在明确的认证错误时才清除token
        if (error.response?.status === 401 || error.message?.includes('token')) {
          userStore.clearToken()
          userStore.clearUserInfo()
          next('/login')
          return
        }

        // 其他错误可能是网络问题，不清除token
        ElMessage.warning('网络连接异常，请稍后重试')
      } finally {
        globalAuth.setInitializing(false)
      }
    }

    // 检查登录状态
    if (!userStore.isLoggedIn) {
      next('/login')
      return
    }

    // 检查角色权限
    if (to.meta.roles && Array.isArray(to.meta.roles)) {
      const userRole = userStore.userInfo?.role
      if (!userRole || !to.meta.roles.includes(userRole)) {
        ElMessage.error('没有权限访问该页面')
        next('/dashboard')
        return
      }
    }
  } else {
    // 已登录用户访问登录页面，重定向到仪表盘
    if (userStore.isLoggedIn && (to.path === '/login' || to.path === '/register')) {
      next('/dashboard')
      return
    }
  }

  next()
})

router.afterEach(() => {
  NProgress.done()
})

export default router
